﻿
namespace NamedBinaryTag
{
	/// <summary>
	/// Represents a Tag containing a byte array.
	/// </summary>
	public sealed class TagByteArray : NamedTag
	{
		private byte[] _value;

		/// <summary>
		/// Obtains or defines the internal byte array.
		/// </summary>
		public byte[] Value
		{
			get { return _value; }
			set { if (_value != value) { _value = value; RaisePropertyChange("Value"); } }
		}

		/// <summary>
		/// Obtains or defines a byte in the internal data.
		/// </summary>
		/// <param name="index">Index of the byte to access.</param>
		/// <returns>The value of the accessed byte.</returns>
		/// <value>The new value for the accessed byte.</value>
		public byte this[int index]
		{
			get { return _value[index]; }
			set { if (_value[index] != value) { _value[index] = value; RaisePropertyChange("Value"); } }
		}

		public override byte TagType
		{
			get { return 7; }
		}

		public override void Read(System.IO.BinaryReader input, bool ignoreName)
		{
			base.Read(input, ignoreName);
			TagInt length = new TagInt();
			length.Read(input, true);
			Value = input.ReadBytes(length.Value);
		}

		public override void Write(System.IO.BinaryWriter output, bool ignoreName)
		{
			base.Write(output, ignoreName);
			TagInt length = new TagInt();
			length.Value = Value.Length;
			length.Write(output, true);
			output.Write(Value);
		}

		public override string ToString()
		{
			System.Text.StringBuilder builder = new System.Text.StringBuilder(System.Math.Min(_value.Length, 32) * 2 + 1);
			for (int i = 0; i < System.Math.Min(_value.Length, 32); i++)
			{
				builder.Append(_value[i].ToString("X2"));
			}
			if (_value.Length > 32)
				builder.Append("…");
			return string.Format("TagByteArray {{ Name = \"{0}\", Length = {1}, Value = 0x{2} }}", Name, _value.Length, builder);
		}
	}
}
